package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.common.MessageConst;
import com.itheima.common.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName MemberController
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-06-29
 * @Version V1.0
 **/
@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController {
    @Reference
    private ValidateCodeService validateCodeService;
    @Autowired
    JedisPool jedisPool;
    @Reference
    MemberService memberService;

    @RequestMapping("login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        log.debug(map.toString());
        //验证码错误
        if (!validateCodeService.checkValidateCode(telephone, RedisMessageConstant.SENDTYPE_LOGIN, validateCode)) {
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }

        Member member = memberService.findByTelephone(telephone);
        if (member == null) {
            //不是会员 自动注册
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }
        //向客户端写入cookie,使用手机号作为key,保存时长为30分钟
        Jedis jedis = jedisPool.getResource();
        jedis.setex(telephone, 60 * 30, JSON.toJSON(member).toString());
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

}
